package com.xiao.hao.service;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Maps;
import com.xiao.hao.config.UserConfig;
import com.xiao.hao.constant.NumberConstants;
import com.xiao.hao.convertor.XhUserFileConvertor;
import com.xiao.hao.convertor.XhUserInfoConvertor;
import com.xiao.hao.convertor.XhUserInfoFileConvertor;
import com.xiao.hao.convertor.XhUserPastHistoryConvertor;
import com.xiao.hao.entity.XhUserFile;
import com.xiao.hao.entity.XhUserInfo;
import com.xiao.hao.entity.XhUserInfoFile;
import com.xiao.hao.entity.XhUserPastHistory;
import com.xiao.hao.exception.BusinessException;
import com.xiao.hao.facade.XhUserInfoFileFacade;
import com.xiao.hao.mapper.XhUserFileMapper;
import com.xiao.hao.mapper.XhUserInfoFileMapper;
import com.xiao.hao.mapper.XhUserInfoMapper;
import com.xiao.hao.mapper.XhUserPastHistoryMapper;
import com.xiao.hao.req.XhUserInfoFileInsertReq;
import com.xiao.hao.req.XhUserInfoFileQueryPageReq;
import com.xiao.hao.req.XhUserInfoFileUpdateReq;
import com.xiao.hao.resp.XhUserFileResp;
import com.xiao.hao.resp.XhUserInfoFileResp;
import com.xiao.hao.resp.XhUserPastHistoryResp;
import com.xiao.hao.utils.BaseId;
import com.xiao.hao.utils.PageResult;
import com.xiao.hao.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Description 用户档案表 服务实现层
 * @Author xiaohao
 * @Date 2025-03-14 16:55:40
 */
@Service
@Slf4j
public class XhUserInfoFileServiceImpl implements XhUserInfoFileFacade {

    @Resource
    XhUserInfoFileMapper mapper;


    @Resource
    XhUserInfoMapper xhUserInfoMapper;

    @Resource
    XhUserFileMapper xhUserFileMapper;

    @Resource
    XhUserPastHistoryMapper xhUserPastHistoryMapper;


    /**
     * 功能描述: 角色新增
     *
     * @param req
     * @return com.xiao.hao.utils.Result
     * @author xiaohao
     * @date 2025-03-14 16:55:40
     */
    @Override
    public Result insert(XhUserInfoFileInsertReq req) {
        List<XhUserInfoFile> xhUserInfoFiles = mapper.selectList(new LambdaQueryWrapper<XhUserInfoFile>().eq(XhUserInfoFile::getUserInfoId, UserConfig.getUserId()));
        long count = xhUserInfoFiles.stream().filter(f -> f.getNickName().equals(req.getNickName())).count();
        BusinessException.isTrue(count == 0, "昵称重复，请重新添加！！！");
        req.setUserInfoId(UserConfig.getUserId());
        if (NumberConstants.INTEGER_ONE.equals(req.getType())) {
            mapper.update(new XhUserInfoFile(), new LambdaUpdateWrapper<XhUserInfoFile>().eq(XhUserInfoFile::getUserInfoId, UserConfig.getUserId())
                    .set(XhUserInfoFile::getType, NumberConstants.INT_ZERO));
        }
        return Result.succeed(mapper.insert(XhUserInfoFileConvertor.INSTANCE.reqToEntity(req)));
    }


    /**
     * 功能描述: 角色修改
     *
     * @param req
     * @return com.xiao.hao.utils.Result
     * @author xiaohao
     * @date 2025-03-14 16:55:40
     */
    @Override
    public Result update(XhUserInfoFileUpdateReq req) {
        XhUserInfoFile xhUserInfoFile = XhUserInfoFileConvertor.INSTANCE.reqToEntity(req);
        List<XhUserInfoFile> xhUserInfoFiles = mapper.selectList(new LambdaQueryWrapper<XhUserInfoFile>().eq(XhUserInfoFile::getUserInfoId, UserConfig.getUserId()));
        long count = xhUserInfoFiles.stream().filter(f -> f.getNickName().equals(req.getNickName()) && f.getStatus().equals(NumberConstants.INTEGER_ONE)).count();
        BusinessException.isTrue(count == 0, "昵称重复，请重新添加！！！");
        xhUserInfoFile.setUserInfoId(UserConfig.getUserId());
        if (ObjectUtil.isEmpty(req.getId())) {
            req.setId(UserConfig.getUserId());
            XhUserInfo xhUserInfo = XhUserInfoConvertor.INSTANCE.reqToEntity(req);
            xhUserInfoMapper.updateById(xhUserInfo);
        } else {
            XhUserInfoFile xhUserInfoFile1 = mapper.selectById(req.getId());
            BusinessException.isTrue(ObjectUtil.isNotEmpty(xhUserInfoFile1), "非法请求，档案id不存在！！！");
            List<XhUserInfoFile> xhUserInfoFilesTmp = mapper.selectList(new LambdaQueryWrapper<XhUserInfoFile>().eq(XhUserInfoFile::getUserInfoId, UserConfig.getUserId()));
            long countTmp = xhUserInfoFilesTmp.stream().filter(f -> f.getNickName().equals(req.getNickName()) && f.getUserInfoId().equals(UserConfig.getUserId()) && !f.getId().equals(req.getId())).count();
            BusinessException.isTrue(countTmp == 0, "昵称重复，请重新添加！！！");
            if (xhUserInfoFile1.getStatus().equals(NumberConstants.INTEGER_ONE)) {
                req.setId(UserConfig.getUserId());
                XhUserInfo xhUserInfo = XhUserInfoConvertor.INSTANCE.reqToEntity(req);
                xhUserInfoMapper.updateById(xhUserInfo);
            }
            if (NumberConstants.INTEGER_ONE.equals(req.getType())) {
                mapper.update(new XhUserInfoFile(), new LambdaUpdateWrapper<XhUserInfoFile>().eq(XhUserInfoFile::getUserInfoId, UserConfig.getUserId())
                        .set(XhUserInfoFile::getType, NumberConstants.INT_ZERO));
            }
            mapper.updateById(xhUserInfoFile);
        }
        return Result.succeed();
    }


    /**
     * 功能描述: 删除角色
     *
     * @param req
     * @return com.xiao.hao.utils.Result
     * @author xiaohao
     * @date 2025-03-14 16:55:40
     */
    @Override
    public Result delete(BaseId req) {
        return Result.succeed(mapper.deleteById(req.getId()));
    }

    /**
     * 功能描述: 角色分页查询
     *
     * @param req
     * @return com.xiao.hao.utils.PageResult
     * @author xiaohao
     * @date 2025-03-14 16:55:40
     */
    @Override
    public PageResult queryPage(XhUserInfoFileQueryPageReq req) {
        Page<XhUserInfoFile> page = mapper.selectPage(new Page(req.getNum(), req.getSize()), new LambdaQueryWrapper<XhUserInfoFile>()
                .eq(XhUserInfoFile::getUserInfoId, UserConfig.getUserId())
                .eq(XhUserInfoFile::getStatus, NumberConstants.INT_ZERO)
                .orderByDesc(XhUserInfoFile::getCreateTime));
        return PageResult.result(page.getTotal(), XhUserInfoFileConvertor.INSTANCE.entityListToRespList(page.getRecords()));
    }

    @Override
    public Result<XhUserInfoFileResp> queryUserFile(BaseId req) {
        XhUserInfoFile xhUserInfoFile = mapper.selectById(req.getId());
        BusinessException.isTrue(ObjectUtil.isNotEmpty(xhUserInfoFile), "非法请求，没有用户档案信息！！！");
        List<XhUserFile> xhUserFiles = xhUserFileMapper.selectList(new LambdaQueryWrapper<XhUserFile>().in(XhUserFile::getUserInfoFileId, xhUserInfoFile.getId()));
        Map<String, List<XhUserFileResp>> collect1 = Maps.newHashMap();
        Map<String, List<XhUserPastHistoryResp>> collect2 = Maps.newHashMap();
        if (CollUtil.isNotEmpty(xhUserFiles)) {
            List<XhUserFileResp> xhUserFileResps = XhUserFileConvertor.INSTANCE.entityListToRespList(xhUserFiles);
            collect1 = xhUserFileResps.stream().collect(Collectors.groupingBy(XhUserFileResp::getUserInfoFileId));
        }
        List<XhUserPastHistory> xhUserPastHistories = xhUserPastHistoryMapper.selectList(new LambdaQueryWrapper<XhUserPastHistory>().in(XhUserPastHistory::getUserInfoFileId, xhUserInfoFile.getId()));
        if (CollUtil.isNotEmpty(xhUserPastHistories)) {
            List<XhUserPastHistoryResp> xhUserPastHistoryResps = XhUserPastHistoryConvertor.INSTANCE.entityListToRespList(xhUserPastHistories);
            collect2 = xhUserPastHistoryResps.stream().collect(Collectors.groupingBy(XhUserPastHistoryResp::getUserInfoFileId));
        }
        XhUserInfoFileResp xhUserInfoFileResps = XhUserInfoFileConvertor.INSTANCE.entityToResp(xhUserInfoFile);
        xhUserInfoFileResps.setXhUserFileRespList(collect1.get(xhUserInfoFileResps.getId()));
        xhUserInfoFileResps.setXhUserPastHistoryRespList(collect2.get(xhUserInfoFileResps.getId()));
        return Result.succeed(xhUserInfoFileResps);
    }

    @Override
    public Result<List<XhUserInfoFileResp>> queryUserFileNo() {
        List<XhUserInfoFile> xhUserInfoFiles = mapper.selectList(new LambdaQueryWrapper<XhUserInfoFile>().eq(XhUserInfoFile::getUserInfoId, UserConfig.getUserId())
                .orderByDesc(XhUserInfoFile::getCreateTime));
        List<Long> collect = xhUserInfoFiles.stream().map(x -> x.getId()).collect(Collectors.toList());
        List<XhUserFile> xhUserFiles = xhUserFileMapper.selectList(new LambdaQueryWrapper<XhUserFile>().in(XhUserFile::getUserInfoFileId, collect));
        Map<String, List<XhUserFileResp>> collect1 = Maps.newHashMap();
        Map<String, List<XhUserPastHistoryResp>> collect2 = Maps.newHashMap();
        if (CollUtil.isNotEmpty(xhUserFiles)) {
            List<XhUserFileResp> xhUserFileResps = XhUserFileConvertor.INSTANCE.entityListToRespList(xhUserFiles);
            collect1 = xhUserFileResps.stream().collect(Collectors.groupingBy(XhUserFileResp::getUserInfoFileId));
        }
        List<XhUserPastHistory> xhUserPastHistories = xhUserPastHistoryMapper.selectList(new LambdaQueryWrapper<XhUserPastHistory>().in(XhUserPastHistory::getUserInfoFileId, collect));
        if (CollUtil.isNotEmpty(xhUserPastHistories)) {
            List<XhUserPastHistoryResp> xhUserPastHistoryResps = XhUserPastHistoryConvertor.INSTANCE.entityListToRespList(xhUserPastHistories);
            collect2 = xhUserPastHistoryResps.stream().collect(Collectors.groupingBy(XhUserPastHistoryResp::getUserInfoFileId));
        }
        List<XhUserInfoFileResp> xhUserInfoFileResps = XhUserInfoFileConvertor.INSTANCE.entityListToRespList(xhUserInfoFiles);
        Map<String, List<XhUserFileResp>> finalCollect1 = collect1;
        Map<String, List<XhUserPastHistoryResp>> finalCollect = collect2;
        xhUserInfoFileResps.forEach(x -> {
            x.setXhUserFileRespList(finalCollect1.get(x.getId()));
            x.setXhUserPastHistoryRespList(finalCollect.get(x.getId()));
        });
        return Result.succeed(xhUserInfoFileResps);
    }

}



